import { SetupContext, computed, inject, ref } from "vue";
import { ClipboardProps } from "../clipboard.props";
import { UseClipboard } from "./types";

export function useClipboard(
    props: ClipboardProps,
    context: SetupContext
): UseClipboard {

    const NotifyService: any = inject('NotifyService');
    const motion = ref(props.motion);
    const modelValue = ref(props.modelValue);
    const className = ref(props.className);
    const size = ref(props.size);
    const disabled = ref(props.disabled);
    const text = ref(props.text);
    const style = ref(props.style);
    const target = ref(props.target);

    const clipboardStyle = computed(() => {
        const styleObject = {
             color: '#9ba0aa',
             'pointer-events': disabled.value?'none':'auto',
             cursor: disabled.value?'not-allowed':'pointer'
        } as Record<string, any>;
        return styleObject;
    });


    const clipboardDivClass = computed(() => {
        const classObject = {
            'clipboard': true,
            'clipboard-size-large': size.value === 'large',
            'clipboard-size-middle': size.value === 'middle',
            'clipboard-size-small': size.value === 'small'
        } as Record<string, boolean>;
        return classObject;
    });

    const iconClass = computed(() => {
        const classObject = {
            'f-icon': true,
            'f-icon-copy': motion.value === 'copy',
            'f-icon-cut': motion.value === 'cut'
        } as Record<string, boolean>;
        return classObject;
    });

    async function onClickDiv(event: Event) {
        event.stopPropagation();
        let action = "复制"; 
        let targetElement  = document.querySelector(target.value);
        if(targetElement){
            await navigator.clipboard.writeText(targetElement['value']);

            if(motion.value === 'cut'){
                targetElement['value'] = '';
                action = "剪切"; 
            }

            notify(action + '成功');
            context.emit('onSuccess');
        }else{  
            notify(action + '失败，未获取到页面元素');
            context.emit('onError');
        }      
    }

    function notify(content:String){
        NotifyService.show({
            showCloseButton: false,
            timeout: 1000,
            animate: 'fadeIn',
            toasts: [{ type: 'string', title: '提示', msg: content, timeout: 1000 }],
        });
    }

    function animate(){
        document.querySelector(target.value);
    }

    return { clipboardStyle,text,motion, modelValue, className, size, disabled, iconClass, style,target,onClickDiv,clipboardDivClass };
}
